<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item  prop="lightNo">
        <el-input
          v-model="queryParams.lightNo"
          placeholder="请输入灯杆编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- 开灯按钮 -->
        <el-button
          type="success"
          :plain="selectedRow.length === 0"
          size="mini"
          :disabled="selectedRow.length === 0"
          @click="handleTurnO(selectedRow)"
        >
          <i class="el-icon-video-play" style="font-size: 1.3em; margin-right: 6px;"></i>
          开灯
        </el-button>
        <!-- 关灯按钮 -->
        <el-button
          type="danger"
          :plain="selectedRow.length === 0"
          size="mini"
          :disabled="selectedRow.length === 0"
          @click="handleTurnOf(selectedRow)"
        >
          <i class="el-icon-video-pause" style="font-size: 1.3em; margin-right: 6px;"></i>
          关灯
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['iot:lightpole:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['iot:lightpole:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:lightpole:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['iot:lightpole:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="lightpoleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="灯杆ID" align="center" prop="id" />
      <el-table-column label="客户名称" align="center" prop="adminNickname" />
      <el-table-column label="项目名称" align="center" prop="faProject.projectname" />
      <el-table-column label="灯杆序号" align="center" prop="lightNo" />
      <el-table-column label="灯杆名称" align="center" prop="lightName" />
      <el-table-column label="灯在线状态" align="center" prop="lightonline">
        <template slot-scope="scope">
          <img :src="getStatusImags(scope.row.lightonline)" alt="在线状态" />
        </template>
      </el-table-column>
      <el-table-column label="工作状态" align="center" prop="faHgbox.lightStatus">
        <template slot-scope="scope">
          <div class="status-container">
            <img
              :src="getLightswitchImags(scope.row.faHgbox ? scope.row.faHgbox.lightStatus : 0)"
              alt="工作状态"
              :class="{
          'active-status': scope.row.lightStatus === '1',
          'inactive-status': scope.row.lightStatus === '0'
        }"
              style="width: 22px; height: 22px;"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" >
        <template slot-scope="scope">
          {{(scope.row.createtime)}}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:lightpole:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:lightpole:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改灯杆对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="客户名称" prop="nickName">
          <el-select
            v-model="form.userId"
            placeholder="请选择客户名称"
            filterable
            style="width: 100%"
            @change="handleNicknameChange"
          >
            <el-option
              v-for="item in options"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="项目名称" prop="projectId">
          <el-select
            v-model="selectedProjectName"
            placeholder="请选择项目名称"
            filterable
            style="width: 100%"
            @change="handleProjectnameChange"
          >
            <el-option
              v-for="item in projectnameOptions"
              :key="item.id"
              :label="item.projectname"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="灯控序号" prop="lightNo">
          <el-input v-model="form.lightNo" placeholder="请输入灯控序号" />
        </el-form-item>
        <el-form-item label="灯杆名称" prop="lightName">
          <el-input v-model="form.lightName" placeholder="请输入灯控序号" />
        </el-form-item>
        <el-form-item label="经度" prop="lng">
          <el-input v-model="form.lng" placeholder="请输入经度" @click.native="openMapDialog('lng')" />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度" @click.native="openMapDialog('lat')" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="监控序号" prop="ysNoun">
          <el-input v-model="form.ysNoun" placeholder="请输入监控序号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <!--      <div id="mapContainer" style="width:100%;height:500px;"></div>-->
    </el-dialog>
    <el-dialog
      title="选择位置"
      :visible.sync="mapDialogVisible"
      width="50%"
      append-to-body
      :before-close="handleMapDialogClose"
      :show-close="false"
    >
      <el-autocomplete
        v-model="searchInput"
        placeholder="请输入搜索地点"
        :fetch-suggestions="querySearchAsync"
        @select="handleSelect"
        :trigger-on-focus="false"
        :loading="loading"
      ></el-autocomplete>
      <div id="mapContainer" class="map-container" style="height: 400px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="mapDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmMapLocation">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listLightpole,
  getLightpole,
  delLightpole,
  addLightpole,
  updateLightpole,
  listadmin
} from '@/api/iot/lightpole'
import { options } from 'runjs'
import { Adminlist, listProject } from '@/api/iot/faproject'
import Template from '@/views/iot/template/index.vue'
import { loadBMap } from '@/utils/map'
import request from '@/utils/request'
import { updateHgbox } from '@/api/iot/hgbox'
import { listUser } from '@/api/iot/tool'
import row from 'element-ui/packages/row'

export default {
  name: "Lightpole",
  components: { Template },
  data() {
    return {
      pollInterval: null, // 轮询定时器
      selectedRow: [], // 用于存储选中的设备
      selectedNickname: '', // 存储选中的客户名称
      selectedProjectname: '', // 存储选中的项目名称
      dialogVisible: false,
      mapDialogVisible: false,
      selectedAdminId: null,
      selectedProjectId: null,
      selectedProjectName: null,
      selectedField: '', // 控制地图弹窗是否显示
      mapInstance: null,
      marker: null,
      selectedLocation: {},
      nicknamesOptions: [],
      projectnameOptions: [],
      searchInput: '',
      geocoder: null, // 地理编码器
      localSearch: null, // 地区搜索功能
      searchResult: null, // 搜索结果
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 灯杆表格数据
      lightpoleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        adminId: null,
        lightNo: null,
        lightName: null,
        projectId: null,
        lat: null,
        lng: null,
        refreshtime: null,
        createtime: null,
        updatetime: null,
        deletetime: null,
        weigh: null,
        lightnoF: null,
        lighton: null,
        lightonline: null,
        lightswitch: null,
        lux: null,
        lightswitch2: null,
        lightonline2: null,
        screenswitch: null,
        status: null,
        state: null,
        itemsId: null,
        screenNoun: null,
        cameraType: null,
        ysNoun: null,
        ysAppkey: null,
        ysAppsecret: null,
        ysState: null,
        rtmp: null,
        apiId: null,
        airNoun: null,
        airDeviceid: null,
        airLastUpdateTime: null,
        airOnline: null,
        ysswitch: null,
        airswitch: null,
        fivegswitch: null,
        isdouble: null,
        hasScreen: null,
        lightType: null,
        chargingswitch: null,
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        // nickName: [
        //   { required: true, message: "客户名称不能为空", trigger: "blur" }
        // ],
        // projectname: [
        //   { required: true, message: "项目名称不能为空", trigger: "blur" }
        // ],
        // lightNo: [
        //   { required: true, message: "灯控序号", trigger: "blur" }
        // ],
      }
    };
  },
  created() {
    this.getList();
    this.fetchNicknames();
    this.fetchProjectnames();
    this.fetchUsers();
    this.startPolling(); // 开始轮询
  },
  async mounted() {
    await this.fetchNicknames();  // 在组件挂载后加载客户名称
    this.getList();  // 加载灯杆列表
  },
  methods: {
    // 处理开灯事件
    handleTurnO() {
      const selectedRow = this.selectedRow;
      if (selectedRow.length === 0) {
        this.$message.warning('请选择设备进行操作。');
        return;
      }
      const requests = selectedRow.map(row => {
        if (!row.lightNo) {
          this.$message.error('选中的设备缺少设备编号');
          return null;
        }
        return this.publish({
          sno: row.lightNo,
          productKey: "a1vJ7tC7nM0",
          thingData: {
            params: {
              lightStatus: 1
            }
          }
        });
      }).filter(request => request !== null);

      Promise.all(requests)
        .then(() => {
          this.$message.success('开灯成功', { duration: 2000 });
          this.getList();
        })
        .catch(error => {
          console.error("开灯失败:", error);
          this.$message.error("开灯失败");
        });
    },

// 处理关灯事件
    handleTurnOf() {
      const selectedRow = this.selectedRow;
      if (selectedRow.length === 0) {
        this.$message.warning('请选择设备进行操作。');
        return;
      }

      const requests = selectedRow.map(row => {
        if (!row.lightNo) {
          this.$message.error('选中的设备缺少设备编号');
          return null;
        }
        return this.publish({
          sno: row.lightNo,
          productKey: "a1vJ7tC7nM0",
          thingData: {
            params: {
              lightStatus: 0
            }
          }
        });
      }).filter(request => request !== null);

      Promise.all(requests)
        .then(() => {
          this.$message.success('关灯成功', { duration: 2000 });
          this.getList();
        })
        .catch(error => {
          console.error("关灯失败:", error);
          this.$message.error("关灯失败");
        });
    },
    publish(snThing) {
      console.log('发送的数据:', JSON.stringify(snThing));
      return request({
        url: '/mqtt/backclient/publish',
        method: 'post',
        data: snThing,
        headers: {
          'Content-Type': 'application/json'
        }
      })
    },
    //更新设备状态
    updateDeviceStatus(selectedRow, successMessage) {
      const promises = selectedRow.map(row => updateLightpole(row));
      Promise.all(promises)
        .then(() => {
          this.$message.success(successMessage, { duration: 2000 });
          this.getList(); // 重新获取设备列表
        })
        .catch(error => {
          console.error("更新设备状态失败:", error);
          this.$message.error("更新设备状态失败");
        });
    },
    getStatusImags(status) {
      return status === 1
        ? require('@/assets/bigScreen/img/wifion.png')
        : require('@/assets/bigScreen/img/wifi.png');
    },
    getLightswitchImags(status) {
      return status === '1'
        ? require('@/assets/bigScreen/img/light_on.png')
        : require('@/assets/bigScreen/img/light_off.png');
    },
    options,
    formatDate(timestamp) {
      const date = new Date(timestamp * 1000); // 将秒转换为毫秒
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}` ;
    },
    // 获取用户列表数据
    async fetchUsers() {
      try {
        const response = await listUser();
        if (response && response.rows) {
          this.options = response.rows.map(user => ({
            userId: user.userId,
            nickName: user.nickName
          }));
          console.log("获取用户列表数据", this.options);
        }
      } catch (error) {
        console.error('获取用户列表失败', error);
      }
    },
    // 客户名称下拉框
    async fetchNicknames() {
      try {
        const response = await listUser({});
        console.log("获取用户数据:", response);  // 确保数据格式正确
        if (response && response.rows && Array.isArray(response.rows)) {
          this.options = response.rows.map(item => ({
            userId: item.userId,
            nickName: item.nickName
          }));
        } else {
          console.error('响应数据格式不正确');
        }
      } catch (error) {
        console.error('获取用户数据失败:', error);
      }
    },

    // 客户名称变化处理
    handleNicknameChange(selectedId) {
      const selectedOption = this.options.find(option => option.userId === selectedId);
      if (selectedOption) {
        console.log(`Selected ID: ${selectedId}, nickName: ${selectedOption.nickName}`);
        this.form.nickName = selectedOption.nickName;  // 显示选择的用户昵称
        this.form.adminId = selectedOption.userId;    // 将选择的 userId 存入 adminId 字段
      }
    },

    //项目名称下拉框
    async fetchProjectnames() {
      try {
        const response = await listProject({});
        if (response && Array.isArray(response.rows)) {
          this.projectnameOptions = response.rows.map(item => ({
            id: item.id,  // 用于存储的项目 ID
            projectname: item.projectname,  // 用于展示的项目名称
          }));
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    handleProjectnameChange(value) {
      // value 是选中的项目 ID
      const selectedData = this.projectnameOptions.find(option => option.id === value);
      if (selectedData) {
        // 打印选中的项目 ID 和 项目名称
        console.log('Selected Project ID:', selectedData.id);
        console.log('Selected Project Name:', selectedData.projectname);
        // 更新 selectedProjectId 和表单中的 projectname 字段
        this.selectedProjectId = selectedData.id;
        this.form.projectname = selectedData.projectname;
        this.form.projectId = selectedData.id;
      } else {
        console.error('No matching data found for value:', value);
      }
    },
    //地图
    async getLatLng() {
      try {
        const BMap = await loadBMap();
        this.initMap(BMap);
      } catch (error) {
        console.error("Failed to load Baidu Map:", error);
      }
    },
    // 初始化百度地图
    initMap(BMap) {
      // 创建地图实例
      this.mapInstance = new BMap.Map("mapContainer");

      // 初始化时设置地图的中心位置和缩放级别
      const initialPoint = new BMap.Point(119.980343, 31.816579);
      this.mapInstance.centerAndZoom(initialPoint, 18);

      // 创建地理编码器实例
      this.geocoder = new BMap.Geocoder();

      // 创建MapTypeControl实例，只显示普通地图类型
      const mapTypeControl = new BMap.MapTypeControl({
        mapTypes: [BMAP_NORMAL_MAP] // 只显示二维平面地图
      });
      this.mapInstance.addControl(mapTypeControl);

      this.mapInstance.enableScrollWheelZoom(true);

      // 初始化标记图标
      const icon = this.createIcon();

      // 创建并添加标记
      this.createMarker(initialPoint, icon);

      // 将标记设为可拖动
      this.marker.enableDragging();
      this.marker.addEventListener("dragend", (e) => {
        this.selectedLocation = { lng: e.point.lng, lat: e.point.lat };
      });

      // 添加地图点击事件监听
      this.mapInstance.addEventListener("click", (e) => {
        this.handleMapClick(e);
      });
    },
// 创建标记图标
    createIcon() {
      const iconUrl = require('@/assets/bigScreen/img/微信图片_20241209154934-removebg-preview.png');
      const iconSize = new BMap.Size(25, 80); // 设置图标大小
      return new BMap.Icon(iconUrl, iconSize);
    },

// 创建并添加标记
    createMarker(point, icon) {
      if (this.marker) {
        this.mapInstance.removeOverlay(this.marker); // 如果已有标记则移除
      }
      this.marker = new BMap.Marker(point, { icon: icon });
      this.mapInstance.addOverlay(this.marker);
    },

// 处理地图点击事件
    handleMapClick(e) {
      const point = e.point;
      const { lng, lat } = point;

      // 更新标记和位置
      this.createMarker(point, this.createIcon());

      // 将标记设为可拖动
      this.marker.enableDragging();

      // 更新选中的经纬度
      this.selectedLocation = { lng, lat };

      // 使用地理编码器获取地址信息并设置标签
      if (this.geocoder) {
        this.geocoder.getLocation(point, (result) => {
          if (result && result.address) {
            const labelContent = `地址: ${result.address}<br>经度: ${lng}<br>纬度: ${lat}`;
            this.setMarkerLabel(labelContent);
          }
        });
      }

      // 更新表单数据
      this.form.lng = lng;
      this.form.lat = lat;

      // 触发事件，传递经纬度信息给父组件
      this.$emit('mapClickLocation', { lng, lat });
    },
// 自动定位功能
//     autoLocate(BMap) {
//       const geolocation = new BMap.Geolocation();
//
//       geolocation.getCurrentPosition(
//         (result) => {
//           // 先检查 result 和 result.point 是否有效
//           if (result && result.point && this.mapInstance) {
//             const point = result.point;
//             this.mapInstance.centerAndZoom(point, 12);
//             // 设置标记位置
//             this.marker.setPosition(point);
//             this.selectedLocation = { lng: point.lng, lat: point.lat };
//           } else {
//             console.error("定位失败，未能获取有效的地理位置");
//             // 定位失败时，使用默认中心点
//             this.mapInstance.centerAndZoom(new BMap.Point(119.980343,31.816579), 12);
//           }
//         },
//         (error) => {
//           console.error("定位失败: ", error.message);
//           // 定位失败时，使用默认中心点
//           if (this.mapInstance) {
//             this.mapInstance.centerAndZoom(new BMap.Point(119.980343,31.816579), 12);
//           }
//         }
//       );
//     },

// 设置标记标签
    setMarkerLabel(content) {
      const label = new BMap.Label(content, { offset: new BMap.Size(20, 25) });
      label.setStyle({
        color: "black",
        fontSize: "12px",
        lineHeight: "18px",
        fontFamily: "微软雅黑",
        border: "1px solid #c3c3c3",
        backgroundColor: "#f5f5f5",
        padding: "5px",
        borderRadius: "3px"
      });
      this.marker.setLabel(label);
    },

// 打开地图选择对话框
    openMapDialog(field) {
      this.selectedField = field;
      this.mapDialogVisible = true;
      this.searchInput = ''; // 清空搜索框内容

      if (!this.mapInstance) {
        this.getLatLng();
      } else {
        this.querySearchAsync(''); // 开始加载位置
      }
    },

// 确认选中的位置
    confirmMapLocation() {
      const { lng, lat } = this.selectedLocation;

      if (lng && lat) {
        // 更新表单中的经纬度
        this.form.lng = lng;
        this.form.lat = lat;

        // 传递经纬度给父组件
        this.$emit('confirmMapLocation', this.selectedLocation);

        // 关闭地图弹窗
        this.mapDialogVisible = false;
      } else {
        console.error("没有选择有效的位置信息");
      }
    },

// 关闭地图弹窗时的处理
    handleMapDialogClose() {
      this.selectedLocation = {};
      if (this.marker) {
        this.mapInstance.removeOverlay(this.marker); // 关闭时移除标记
      }
      this.mapInstance.clearOverlays(); // 清除所有覆盖物
    },

// 异步搜索位置
    querySearchAsync(queryString, cb = () => {}) {
      if (!queryString) {
        cb([]); // 如果没有查询字符串，调用回调并传递空数组
        return;
      }

      this.loading = true;
      const local = new BMap.LocalSearch(this.mapInstance, {
        onSearchComplete: (results) => {
          this.loading = false;
          const suggestions = results && results.getNumPois()
            ? [...Array(results.getNumPois())].map((_, i) => results.getPoi(i))
              .filter(poi => poi !== undefined)
              .map(poi => ({
                value: `${poi.title || ''} (${poi.address || ''})`,
                address: poi.address || '',
                point: poi.point
              }))
            : [];

          cb(suggestions); // 调用回调函数并传递结果

          if (suggestions.length > 0) {
            // 处理第一个搜索结果
            this.handleSelect(suggestions[0]);
          }
        }
      });

      local.search(queryString); // 开始搜索
    },

    // 处理选择的地址
    handleSelect(item) {
      // 如果已经存在标记，移除旧的标记
      if (this.marker) {
        this.mapInstance.removeOverlay(this.marker); // 移除旧的标记
      }

      // 创建新的标记，并指定使用本地图片作为标记图标
      const newIcon = this.createIcon();  // 创建新的图标
      this.marker = new BMap.Marker(item.point, { icon: newIcon });  // 使用自定义图标的标记
      this.mapInstance.addOverlay(this.marker);  // 将新标记添加到地图中

      // 将地图缩放到选择位置
      this.mapInstance.centerAndZoom(item.point, 12);

      // 更新选中的经纬度
      this.selectedLocation = { lng: item.point.lng, lat: item.point.lat };
      this.form.lng = item.point.lng;
      this.form.lat = item.point.lat;

      // 更新标记的标签内容
      const labelContent = `地址: ${item.address || '未知地址'}<br>经度: ${item.point.lng}<br>纬度: ${item.point.lat}`;
      this.setMarkerLabel(labelContent);  // 设置标记标签
    },
    // 查询灯杆列表
    getList() {
      this.loading = true;
      listLightpole(this.queryParams).then(response => {
        console.log("9999",response)
        this.lightpoleList = response.rows.map(row => ({
          ...row,
          adminNickname: this.getNicknameById(row.adminId),  // 映射 adminId 和 nickName
        }));

        this.total = response.total;
        this.loading = false;
      });
    },
    startPolling() {
      // 每五分钟秒轮询一次数据
      this.pollInterval = setInterval(this.getList, 300000);
    },
// 根据 adminId 获取对应的名称
    getNicknameById(adminId) {
      // 确保 this.options 是一个数组
      if (Array.isArray(this.options)) {
        const option = this.options.find(option => option.userId === adminId);
        return option ? option.nickName : '';  // 如果找到对应选项则返回 nickName，否则返回空字符串
      }
      // 如果 this.options 不是一个数组，返回空字符串
      return '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        adminId: null,
        lightNo: null,
        lightName: null,
        projectId: null,
        lat: null,
        lng: null,
        remark: null,
        refreshtime: null,
        createtime: null,
        updatetime: null,
        deletetime: null,
        weigh: null,
        lightnoF: null,
        lighton: null,
        lightonline: null,
        lightswitch: null,
        lux: null,
        lightswitch2: null,
        lightonline2: null,
        screenswitch: null,
        status: "0",
        state: null,
        itemsId: null,
        screenNoun: null,
        cameraType: null,
        ysNoun: null,
        ysAppkey: null,
        ysAppsecret: null,
        ysState: null,
        rtmp: null,
        userId: null,
        apiId: null,
        airNoun: null,
        airDeviceid: null,
        airLastUpdateTime: null,
        airOnline: null,
        ysswitch: null,
        airswitch: null,
        fivegswitch: null,
        isdouble: null,
        hasScreen: null,
        lightType: null,
        chargingswitch: null,
      };
      this.resetForm("form");
      this.selectedProjectId = '';
      this.selectedNickname = '';
      this.selectedProjectname = '';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.selectedRow = selection;
    },
    handleAdd() {
      this.reset(); // 重置表单
      this.open = true;
      this.title = "添加灯杆";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getLightpole(id).then(response => {
        let data = response.data;
        this.form = data;
        // 设置客户名称下拉框回显
        this.form.userId = data.adminId;
        this.form.projectId = data.projectId;
        // 设置项目名称下拉框回显
        // this.selectedProjectId = data.faProject?data.faProject.projectname:null;
        this.selectedProjectId = data.projectId;
        this.selectedProjectName = data.faProject?data.faProject.projectname:null;
        this.open = true;
        this.title = "修改灯杆";
      }).catch(err => {
        console.log("err")
        console.log(err)
      })
    },
    submitForm() {
      // 手动验证表单
      if (!this.form.adminId) {
        this.$message.error('客户名称不能为空');
        return;
      }
      if (!this.selectedProjectId) {
        this.$message.error('项目名称不能为空');
        return;
      }
      if (!this.form.lightNo) {
        this.$message.error('灯控序号不能为空');
        return;
      }
      const dataToSubmit = {
        lightName: this.form.lightName,
        remark: this.form.remark,
        lightNo: this.form.lightNo,
        adminId: this.form.adminId,  // 使用 form.adminId
        projectId: this.selectedProjectId,
        lng: this.form.lng,
        lat: this.form.lat,
        ysNoun: this.form.ysNoun
      };
      if (this.form.id != null) {
        // 更新操作
        updateLightpole({ ...dataToSubmit, id: this.form.id }).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        // 新增操作
        addLightpole(dataToSubmit).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除灯杆编号为"' + ids + '"的数据项？').then(function() {
        return delLightpole(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/lightpole/export', {
        ...this.queryParams
      }, `lightpole_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
#searchInput {
  position: absolute;
  top: 100px;
  left: 350px;
  z-index: 9999; /* 确保在地图之上 */
  background: white;
  padding: 8px;
  width: 290px;
}

</style>
